﻿/*  ----------------------------------------------------------------------------
 *  SysServer
 *  ----------------------------------------------------------------------------
 *  File:       BufferManager.cs
 *  Creater:     SEEN\MistSeen
 *  ----------------------------------------------------------------------------
 *  $Date: 2010-09-06 10:36:01 +0000 (Mon, 06 Sep 2010) $
 *  $Rev: 15 $
 *  $Author: ScorDeity $
 *  $URL: http://sysserver.googlecode.com/svn/trunk/src/SysServer/Sock/BufferManager.cs $
 *  $Id: BufferManager.cs 15 2010-09-06 10:36:01Z ScorDeity $
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;

namespace SysServer.Sock
{
    internal class BufferManager
    {
        private int _TotalByteInBufferBlokc;
        private byte[] _BufferBlock;
        private Stack<int> _FreeIndexPool;
        private int _CurrentIndex;
        private int _BuffferSize;


        public BufferManager(int totalBytes, int bufferSize)
        {
            this._TotalByteInBufferBlokc = totalBytes;
            this._CurrentIndex = 0;
            this._BuffferSize = bufferSize;
            this._FreeIndexPool = new Stack<int>();
        }

        internal void InitBuffer()
        {
            this._BufferBlock = new byte[this._TotalByteInBufferBlokc];
        }
        internal bool SetBuffer(SocketAsyncEventArgs args)
        {
            if (this._FreeIndexPool.Count > 0)
            {
                args.SetBuffer(this._BufferBlock, this._FreeIndexPool.Pop(), this._BuffferSize);
            }
            else
            {
                if ((this._TotalByteInBufferBlokc - this._BuffferSize) < this._CurrentIndex)
                {
                    return false;
                }
                args.SetBuffer(this._BufferBlock, this._CurrentIndex, this._BuffferSize);
                this._CurrentIndex += this._BuffferSize;
            }
            return true;
        }
        internal void FreeBuffer(SocketAsyncEventArgs args)
        {
            this._FreeIndexPool.Push(args.Offset);
            args.SetBuffer(null,0, 0);
        }

    }
}